package com.example.common.utils;

import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Build;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

/**
 * @author skygge
 * @Date on 2020-02-25.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：动态申请权限
 */
public class PermissionUtil {

    public static void requestPermission(Activity activity, String[] permissions){
        //如果没有权限请求权限
        if (checkPermissions(activity, permissions)){
            return;
        }
        ActivityCompat.requestPermissions(activity, permissions, 1);
    }

    /**
     * 检查是否已被授权权限
     * @param permissions
     * @return
     */
    private static boolean checkPermissions(Activity activity, String[] permissions) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED ||
                    ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) {
                return false;
            }
        }
        return true;
    }

}
